package com.pvdnc.nsocket;

import com.pvdnc.nsocket.log.SLog;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NamedRunnableMap<R extends Runnable> {
    private static final SLog LOG=new SLog(NamedRunnableMap.class);

    private final Map<String, List<R>> mMap=new HashMap<>();

    public void callAll(String name){
        List<R> list=mMap.get(name);
        for (R runnable:list){
            runnable.run();
        }
    }

    private List<R> getOrCreate(String name){
        List<R> list =mMap.get(name);
        if(list==null) {
            list = new ArrayList<>();
        }
        return list;
    }

    public void put(String name,R runnable,boolean allowOverride){
        List<R> list= getOrCreate(name);
        if(list.contains(runnable)
                &&!allowOverride){
            LOG.e("cannot override event:"+name+" -> "+runnable);
            return;
        }
        list.add(runnable);
        mMap.put(name,list);
    }
}
